package com.cnhis.drgs.core.dao;
import com.cnhis.drgs.core.util.ReflectUtil;
import com.cnhis.drgs.core.vo.Page;
import com.cnhis.drgs.util.Util;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class DbHelper implements Dao {

    public abstract Connection getConnection();

    /**
     * 获取列头字符串
     *
     * @param rs ResultSet
     * @return
     * @throws Exception
     */
    private String[] getColumnNames(ResultSet rs) throws Exception {
        ResultSetMetaData rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        String[] columnNames = new String[count];
        for (int i = 0; i < count; i++) {
            columnNames[i] = rsmd.getColumnLabel(i + 1);
        }
        return columnNames;
    }

    public Page queryPageMap(Page page, String sql, Object... params) {
        String countSql = "SELECT COUNT(1) FROM (" + sql + ") t";
        int rowCount = getCount(countSql, params);
        page.setRowCount(rowCount);
        sql += " LIMIT " + page.getOffset() + "," + page.getPageSize();
        List<Map<String, Object>> list = queryListMap(sql, params);
        page.setList(list);
        return page;
    }


    public List<Map<String, Object>> queryListMap(String sql, Object... params) {
        List<Map<String, Object>> list = new ArrayList<>();
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            if (Util.isArrayNotEmpty(params)) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            rs = ps.executeQuery();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                for (String column : getColumnNames(rs)) {
                    map.put(column, rs.getObject(column));
                }
                list.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(rs, ps, conn);
        }
        return list;
    }

    public Map<String, Object> queryFirstMap(String sql, Object... params) {
        List<Map<String, Object>> list = queryListMap(sql, params);
        if (Util.isCollectionNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }


    public <T> Page queryPage(Page page, String sql, Class<T> clazz, Object... params) {
        String countSql = "SELECT COUNT(1) FROM (" + sql + ") t";
        int rowCount = getCount(countSql, params);
        page.setRowCount(rowCount);
        sql += " LIMIT " + page.getOffset() + "," + page.getPageSize();
        List<T> list = queryList(sql, clazz, params);
        page.setList(list);
        return page;
    }

    public <T> List<T> queryList(String sql, Class<T> clazz, Object... params) {
        List<T> list = new ArrayList<>();
        try {
            List<Map<String, Object>> listMap = queryListMap(sql, params);
            if (Util.isCollectionNotEmpty(listMap)) {
                for (Map<String, Object> map : listMap) {
                    T t = clazz.newInstance();
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        try {
                            List<Field> fieldList = ReflectUtil.getClassAllField(clazz);
                            if (Util.isCollectionNotEmpty(fieldList)) {
                                for (Field field : fieldList) {
                                    if (field.getName().equalsIgnoreCase(entry.getKey())) {
                                        ReflectUtil.setObjectProperty(t, field.getName(), entry.getValue());
                                    }
                                }
                            }
                        } catch (Exception ignored) {
                        }
                    }
                    list.add(t);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public <T> T queryFirst(String sql, Class<T> clazz, Object... params) {
        List<T> list = queryList(sql, clazz, params);
        if (Util.isCollectionNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    public int getCount(String sql, Object... params) {
        Map<String, Object> map = queryFirstMap(sql, params);
        if (map != null) {
            for (Map.Entry<String, Object> entry : map.entrySet()) {
                return Integer.parseInt(entry.getValue().toString());
            }
        }
        return 0;
    }

    /**
     * 新增
     *
     * @param sql
     * @param params
     * @return 受影响的行数
     */
    public int insert(String sql, Object... params) {
        return insert0(sql, false, params);
    }

    /**
     * 新增(返回自增长id)
     *
     * @param sql
     * @param params
     * @return
     */
    public int insertAuto(String sql, Object... params) {
        return insert0(sql, true, params);
    }

    private int insert0(String sql, boolean pkAuto, Object... params) {
        int result = 0;
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = getConnection();
            ps = conn.prepareStatement(sql);
            if (Util.isArrayNotEmpty(params)) {
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i + 1, params[i]);
                }
            }
            result = ps.executeUpdate();
            if (pkAuto) {
                ps = null;
                ResultSet rs = null;
                try {
                    ps = conn.prepareStatement("SELECT @@IDENTITY");
                    rs = ps.executeQuery();
                    if (rs.next()) {
                        result = rs.getInt(1);
                    }
                } finally {
                    close(rs, ps, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            close(null, ps, conn);
        }
        return result;
    }

    public int update(String sql, Object... params) {
        return insert(sql, params);
    }

    public int[] batch(String sql, Object[][] params) {
        throw new RuntimeException("未现实");
    }

    private static void close(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

}
